import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

export const fetchPaginatedData = createAsyncThunk('pagination/fetchPaginatedData', async (params, thunkAPI) => {
  const user = JSON.parse(localStorage.getItem('user'))
  const response = await axios.get(`https://api.redgrowth.app/dollars-api/public/index.php/api/red_growth/mention`, {
    params,
    headers: {
      'Content-Type': 'application/json',
      token: user.token,
    },
  })
  return response.data.data
})

const mentionSlice = createSlice({
  name: 'mention',
  initialState: {
    mentions: [],
    curMention: {
      selected: null,
    },
    paginationConfig: {
      total: 0,
      perPage: 30,
      currentPage: 1,
      lastPage: 0,
      replyType: 'all',
    },
    isLoading: false,
    error: null,
  },
  reducers: {
    setMentions: (state, action) => {
      state.mentions = action.payload
    },
    setCurMention: (state, action) => {
      state.curMention = action.payload
    },
    setPaginationConfig: (state, action) => {
      state.paginationConfig = action.payload
    },
  },
  extraReducers: builder => {
    builder
      .addCase(fetchPaginatedData.pending, state => {
        state.isLoading = true
      })
      .addCase(fetchPaginatedData.fulfilled, (state, action) => {
        state.isLoading = false
        state.mentions = action.payload.data

        state.paginationConfig.total = action.payload.total
        state.paginationConfig.perPage = action.payload.per_page
        state.paginationConfig.currentPage = action.payload.current_page
        state.paginationConfig.lastPage = action.payload.last_page
      })
      .addCase(fetchPaginatedData.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message
      })
  },
})

export const { setMentions, setCurMention, setPaginationConfig } = mentionSlice.actions

export const selectMentions = state => state.mention.mentions
export const selectCurMention = state => state.mention.curMention
export const selectPaginationConfig = state => state.mention.paginationConfig

export default mentionSlice.reducer
